<?php

namespace Package\RedisHelper\Config;

use Package\RedisHelper\Exceptions\RedisConnectionException;

class ConfigLoader
{
    /**
     * 从多种来源加载配置
     *
     * 支持来源:
     * 1. 数组
     * 2. 配置文件路径 (PHP, JSON, INI)
     * 3. 环境变量前缀
     *
     * @param mixed $source
     */
    public static function load($source): RedisConfig
    {
        if ($source instanceof RedisConfig) {
            return $source;
        }
        
        if (is_array($source)) {
            return new RedisConfig($source);
        }
        
        if (is_string($source)) {
            
            // 尝试从环境变量加载
            return self::loadFromEnv($source);
        }
        
        throw new RedisConnectionException("Unsupported configuration source type");
    }
    
    private static function loadFromEnv(string $prefix): RedisConfig
    {
        $config = [];
        
        $envVars = [
            'HOST' => 'host',
            'PORT' => 'port',
            'PASSWORD' => 'password',
            'DATABASE' => 'database',
            'TIMEOUT' => 'timeout',
            'PERSISTENT' => 'persistent',
            'PREFIX' => 'prefix',
            'RETRY_INTERVAL' => 'retry_interval',
            'READ_TIMEOUT' => 'read_timeout',
            'SERIALIZER' => 'serializer',
        ];
        
        foreach ($envVars as $envSuffix => $configKey) {
            $envVar = $prefix . '_' . $envSuffix;
            if (($value = getenv($envVar)) !== false) {
                // 转换数据类型
                if (in_array($envSuffix, ['PORT', 'DATABASE', 'RETRY_INTERVAL'])) {
                    $value = (int)$value;
                } elseif (in_array($envSuffix, ['TIMEOUT', 'READ_TIMEOUT'])) {
                    $value = (float)$value;
                } elseif ($envSuffix === 'PERSISTENT') {
                    $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
                } elseif ($envSuffix === 'SERIALIZER') {
                    $value = constant($value) ?? \Redis::SERIALIZER_PHP;
                }
                
                $config[$configKey] = $value;
            }
        }
        
        return new RedisConfig($config);
    }
}